import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate';

Vue.use(Vuex);

export default new Vuex.Store({
  getters: {
    // 计算购物车商品总金额
    cartSubtotal: state => {
      let sub = 0;
      state.cartItems.forEach(item => (sub += item.count * item.price * 100));
      return sub;
    },
    // 返回购物车商品种类数量
    cartItemCount: state => {
      return state.cartItems.length;
    }
  },
  state: {
    cartItems: [],
    backupCartItems: [],
    // 图片文章id
    articalId: 0,
    list: [], // 商品列表
    // 文章id
    articleId: 0,
    isAddGoodButtonVisible: false
  },
  mutations: {
    // 购物车指定物品数量加1
    plusCartItemCount(state, id) {
      const item = state.cartItems.find(item => item.id === id);
      item && item.count++;
    },
    // 购物车指定物品数量减1
    minusCartItemCount(state, id) {
      const item = state.cartItems.find(item => item.id === id);
      item && item.count--;
    },
    // 购物车指定物品数量变化
    changeCartItemCount(state, args) {
      const item = state.cartItems.find(item => item.id === args[0]);
      item && (item.count = args[1] - 0);
    },
    // 移除购物车内指定物品
    removeCartItem(state, id) {
      const index = state.cartItems.findIndex(item => item.id === id);
      if (index > -1) {
        state.backupCartItems = [...state.cartItems];
        state.cartItems.splice(index, 1);
      }
    },
    // 添加购物车列表
    addCartItem(state, item) {
      const index = state.cartItems.findIndex(it => it.id === item.id);
      if (index < 0) {
        state.cartItems.push(item);
      } else {
        state.cartItems[index].count += item.count - 0;
      }
    },
    rollbackRemove(state) {
      state.cartItems = state.backupCartItems;
      state.backupCartItems = [];
    },
    refreshCartItem() {},
    // 显示顶栏右侧添加按钮
    showAddGoodButton(state) {
      state.isAddGoodButtonVisible = true;
    },
    // 隐藏顶栏右侧添加按钮
    hideAddGoodButton(state) {
      state.isAddGoodButtonVisible = false;
    },
    imgId(state, id) {
      state.articalId = id
    },
    //点击文章后,保存文章id,以便根据文章id获取文章详细数据
    saveId(state, id) {
      state.articleId = id
    }
  },
  actions: {},
  modules: {},
  plugins: [createPersistedState()]
})
